<template>
  <view>
    <view class="upload-container">
      <u-upload
        ref="uploadComponent"
        :action="uploadUrl"
        :auto-upload="true"
        :max-count="maxCount"
        :show-upload-list="false"
        @on-success="handleSuccess"
        @on-error="handleError"
        @on-preview="handlePreview"
      >
        <view slot="addBtn" class="upload-btn" hover-class="upload-btn__hover">
          <u-icon name="camera" size="60"></u-icon>
          <view>上传图片</view>
        </view>
      </u-upload>
      <view class="image-list">
        <block v-for="(image, index) in images" :key="index">
          <view class="image-item">
            <image :src="image.url" mode="aspectFill" class="image-preview"></image>
            <u-icon name="close" size="20" color="#ffffff" class="delete-icon" @click="removeImage(index)"></u-icon>
          </view>
        </block>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MultiImageUpload',
  props: {
    uploadUrl: {
      type: String,
      required: true
    },
    maxCount: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      images: []
    };
  },
  created() {
    console.log('MultiImageUpload 组件已加载');
  },
  methods: {
    handleSuccess(response, file, files) {
      console.log('上传成功', response);
      if (response.status === 200) {
        this.images.push({ url: response.data.url });
      } else {
        this.$u.toast('上传失败');
      }
    },
    handleError(error) {
      console.log('上传失败', error);
      this.$u.toast('上传失败');
    },
    handlePreview(file) {
      console.log('预览文件', file);
    },
    removeImage(index) {
      this.images.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.upload-container {
  padding: 20rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f4f5f6;
  border-radius: 10rpx;
}

.upload-btn__hover {
  background-color: #ebeced;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.image-item {
  position: relative;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.image-preview {
  width: 160rpx;
  height: 160rpx;
}

.delete-icon {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #fa3534;
  border-radius: 50%;
}
</style>
